#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:taotieren

"""
    rpi.gpio 需要 root 权限，板上运行需要使用
    sudo python thingspeak.py
    传感器数据记录到 ThingSpeak 上

"""

import time, os, urllib, urllib3

PERIOD = 60  # 秒
BAES_URL = 'https://api.thingspeak.com/update.json'
KEY = 'DYHHDDKKLU8OV58T'


def send_data(temp):
    data = urllib.urlencode({'api_key': KEY, 'field': temp})
    response = urllib3.urlopen(url=BAES_URL, data=data)
    print(response.read())


def cpu_temp():
    dev = os.popen('/opt/vc/bin/vcgencmd measure_temp')
    cpu_temp = dev.read()[5:-3]
    return cpu_temp


while True:
    temp = cpu_temp()
    print("CPU Temp (C):" + str(temp))
    send_data(temp)
    time.sleep(PERIOD)
